package com.zjun.demo.experimentaldemo.indexbar.suspension

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.text.TextPaint
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.View.MeasureSpec
import android.view.View.MeasureSpec.EXACTLY
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zjun.demo.experimentaldemo.R
import com.zjun.demo.experimentaldemo.app.App.Companion.CONTEXT
import com.zjun.demo.experimentaldemo.indexbar.CountryAdapter

class SuspensionDecoration: RecyclerView.ItemDecoration() {

    private val mTextPaint = TextPaint()

    private val mBgPaint = Paint()

    private var mMeasuredHeight = -1

    private val mMarginStart = dip2px(16f)

    init {
        mTextPaint.run {
            color = Color.parseColor("#333333")
            isFakeBoldText = true
            textSize = sp2px(16f)
        }
        mBgPaint.color = Color.parseColor("#F2F2F2")
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        val adapter = parent.adapter?:return
        try {
            val countryAdapter = adapter as CountryAdapter
            val childCount = parent.childCount
            for (i in 0 until childCount) {
                val child = parent.getChildAt(i)
                val params = child.layoutParams as RecyclerView.LayoutParams
                val position = params.viewLayoutPosition
                if(position in 0 until  countryAdapter.data.size && countryAdapter.data[position].isShowSuspension()){
                    val tag = countryAdapter.data[position].getSuspensionTag()
                    val left = 0f
                    val top = (child.top - mMeasuredHeight).toFloat()
                    val right = parent.width.toFloat()
                    val bottom = child.top.toFloat()
                    c.drawRect(left, top, right, bottom,mBgPaint)
                    mTextPaint.measureText(tag)
                    c.drawText(tag,mMarginStart,child.top - (bottom - top)/2 + mTextPaint.fontMetrics.descent,mTextPaint)
                }
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDrawOver(c, parent, state)
        val adapter = parent.adapter?:return
        val layoutManager = parent.layoutManager?:return
        if(layoutManager is LinearLayoutManager && adapter is CountryAdapter){
            val position =  layoutManager.findFirstVisibleItemPosition()
            val nextPosition = position+1
            val child = parent.findViewHolderForLayoutPosition(position)?.itemView?:return
            if(child.top<=mMeasuredHeight){
                val tag = adapter.data[position].getSuspensionTag()
                var fallback = 0
                if(nextPosition<adapter.data.size){
                    val nextTag = adapter.data[nextPosition].getSuspensionTag()
                    if(nextTag != tag){
                        val nextChild = parent.findViewHolderForLayoutPosition(nextPosition)?.itemView
                        if(nextChild!=null){
                            if(nextChild.top<mMeasuredHeight*2){
                                fallback =  mMeasuredHeight*2 - nextChild.top
                            }
                        }
                    }
                }
                val left = 0f
                val top = 0f - fallback
                val right = parent.width.toFloat()
                val bottom = mMeasuredHeight.toFloat() - fallback
                c.drawRect(left, top, right, bottom,mBgPaint)
                mTextPaint.measureText(tag)
                c.drawText(tag,mMarginStart,(bottom - top)/2 + mTextPaint.fontMetrics.descent - fallback,mTextPaint)
            }
        }
    }

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)
        val adapter = parent.adapter?:return
        val position = (view.layoutParams as RecyclerView.LayoutParams).viewLayoutPosition
        val countryAdapter = adapter as CountryAdapter
        if(position in 0 until countryAdapter.data.size){
            if(mMeasuredHeight == -1){
                val categoryView = LayoutInflater.from(parent.context).inflate(R.layout.item_category,parent,false)
                var lp = categoryView.layoutParams
                if (lp == null) {
                    lp =  ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                    categoryView.layoutParams = lp
                }
                val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(parent.width, View.MeasureSpec.EXACTLY)
                val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(parent.height, View.MeasureSpec.AT_MOST)
                categoryView.measure(widthMeasureSpec,heightMeasureSpec)
                mMeasuredHeight = categoryView.measuredHeight
            }
            val countryEntity = countryAdapter.data[position]
            if(countryEntity.isShowSuspension()){
                outRect.top = mMeasuredHeight
            }
        }
    }

    private fun drawTitleArea(c: Canvas,v:View,params:RecyclerView.LayoutParams,position:Int, recyclerView: RecyclerView,countryAdapter: CountryAdapter){
        val categoryView = LayoutInflater.from(recyclerView.context).inflate(R.layout.item_category,recyclerView,false)
        var lp = categoryView.layoutParams
        if (lp == null) {
            lp =  ViewGroup.LayoutParams(recyclerView.width, mMeasuredHeight)
            categoryView.layoutParams = lp
        }
        categoryView.measure(
            MeasureSpec.makeMeasureSpec(recyclerView.width,EXACTLY),
            MeasureSpec.makeMeasureSpec(mMeasuredHeight,EXACTLY)
        )
        categoryView.layout(0,v.top - categoryView.measuredHeight,recyclerView.width,v.top)
        val tag = countryAdapter.data[position].getSuspensionTag()
        categoryView.findViewById<TextView>(R.id.tvTitle).text = tag
        categoryView.draw(c)
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     * DisplayMetrics类中属性scaledDensity
     */
    private fun sp2px(spValue: Float): Float {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP,
            spValue,
            CONTEXT.resources.displayMetrics
        )
    }

    /**
     * dp转px
     * @param dipValue dp值
     */
    private fun dip2px(dipValue: Float): Float {
        val scale: Float = CONTEXT.resources.displayMetrics.density
        return dipValue * scale + 0.5f
    }


}